<?php

namespace App\Http\Controllers\Message;

use App\Http\Controllers\Controller;
use App\Http\Requests\Message\MessageRequest;
use App\Models\Message\Message;
use App\Repositories\Message\MessageRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
use DB;
use App\Classes\Publish\Publication;
use App\Jobs\Publish\MessageJob;

class MessageController extends Controller
{
    use ModelForm;

    /** @var  MessageRepository */
    private $messageRepository;

    public function __construct(MessageRepository $messageRepo)
    {
        $this->messageRepository = $messageRepo;
    }

    /**
     * Display a listing of the Message.
     *
     * @return Response
     */
    public function index() // Request $request
    {
        return Admin::content(function (Content $content) {

            $content->header(__('message.messages.index_header'));
            $content->description(__('message.messages.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Message.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('message.messages.create_header'));
            $content->description(__('message.messages.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Message in storage.
     *
     * @param MessageRequest $request
     *
     * @return Response
     */
    public function store(MessageRequest $request)
    {
        $input = $request->all();

        $message = $this->messageRepository->create($input);

        Flash::success(__('message.messages.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('message.messages.index'));

    }

    /**
     * Display the specified Message.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $message = $this->messageRepository->findWithoutFail($id);

        if (empty($message)) {
            Flash::error(__('message.messages.not_found'));

            return redirect(route('message.messages.index'));
        }

        return view('message.messages.show')->with('message', $message);

    }

    /**
     * Show the form for editing the specified Message.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('message.messages.edit_header'));
            $content->description(__('message.messages.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Message in storage.
     *
     * @param  int $id
     * @param MessageRequest $request
     *
     * @return Response
     */
    public function update($id, MessageRequest $request)
    {
        $message = $this->messageRepository->findWithoutFail($id);

        if (empty($message)) {
            Flash::error(__('message.messages.not_found'));

            return redirect(route('message.messages.index'));
        }

        $message = $this->messageRepository->update($request->all(), $id);


        Flash::success(__('message.messages.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('message.messages.index'));
    }

    /**
     * Remove the specified Message from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->messageRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('message.messages.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $message = $this->messageRepository->findWithoutFail($id);

        if (empty($message)) {
            Flash::error(__('message.messages.not_found'));

            return redirect(route('message.messages.index'));
        }

        if ($flag = $this->messageRepository->delete($id)) {

            return response()->json(['message' => __('message.messages.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('message.messages.all_up')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够']);
        }
        // 统计需要处理的任务的总数
        // $total_num = DB::table('columns as a')
        //     // ->join('subcolumns as b', 'a.id', '=', 'b.column_id')
        //     ->where(['a.online_status' => 0, 'a.publish_down_status' => 1])
        //     ->pluck('a.id')->unique()->count();
        $result = Publication::getTotalNum(new Message(), [
            [['online_status' => 0], 'ID为以下消息已经上线: '],
            [['publish_down_status' => 1], 'ID为以下消息还未下线发布: '],
        ], '消息上线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '消息上线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new MessageJob(['dispatch', 'up'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('message.messages.all_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够']);
        }
        // 统计需要处理的任务的总数
        $result = Publication::getTotalNum(new Message(), [
            [['online_status' => 1], 'ID为以下消息还没上线'],
        ], '消息下线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '消息下线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new MessageJob(['dispatch', 'down'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('message.messages.publish')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Column(), ['online_status' => 1, 'publish_status' => 0]);
        $result = Publication::getTotalNum(new Message(), [
            [['online_status' => 1], 'ID为以下消息还未上线:'],
            [['publish_status' => 0], 'ID为以下消息已经上线发布:'],
        ], '消息发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data['total_num'] = $total_num;
        // 任务表插入一条记录
        $data = ['task_type' => '消息发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        // (new MessageJob(1, '', $taskid))->handle();exit;
        dispatch(new MessageJob(['dispatch', 'publish'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('message.messages.publish_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Column(), ['online_status' => 0, 'publish_down_status' => 0]);
        $result = Publication::getTotalNum(new Message(), [
            [['online_status' => 0], 'ID为以下消息还未下线: '],
            [['publish_down_status' => 0], 'ID为以下消息已经下线发布: '],
        ], '消息下线发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        // 任务表插入一条记录
        $data = ['task_type' => '消息下线发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new MessageJob(['dispatch', 'publishDown'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 单个,批量上下线功能,单个发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('message.messages.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Message(), $request->ids, [
                    [['online_status' => 0], 'ID为以下消息已经上线: '],
                    [['publish_down_status' => 1], 'ID为以下消息还未下线发布: '],
                ], '消息上线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Message(), $ids, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s')
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '上线操作失败']);
            // 发布
            case 'publish':
                if (Admin::user()->cannot('message.messages.publish')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Column(), $request->ids, ['online_status' => 1, 'publish_status' => 0]);
                $result = Publication::myfilter(new Message(), $request->ids, [
                    [['online_status' => 1], 'ID为以下消息还未上线: '],
                    [['publish_status' => 0], 'ID为以下消息已经上线发布: '],
                ], '消息发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果是批量放入队列中处理
                if (count($ids) > 1) {
                    $data   = ['task_type' => '消息发布', 'user_id' => $user_id, 'total_num' => count($ids)];
                    $taskid = Publication::insertTasks($data);
                    dispatch(new MessageJob(['publish'], $ids, $taskid));
                    $url = route('message.messages.progress');
                    return response()->json(['status' => 'queue', 'content' => $content, 'taskid' => $taskid, 'url' => $url]);
                }
                // 如果是单条数据发布
                $messages      = Message::whereIn('id', $ids)->get();
                $message_datas = MessageJob::makeMessages($messages);
                // print_r($message_datas);exit;

                $result1 = Publication::insertApi('messages', $message_datas);
                $result2 = Publication::updateMany(new Message(), $ids, [
                    'publish_status' => 1,
                    'publish_at'     => date('Y-m-d H:i:s'),
                    'user_id'        => $user_id,
                ]);
                $content = ($result1 && $result2) ? $content : '发布失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线
            case 'down':
                if (Admin::user()->cannot('message.messages.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Column(), $request->ids, ['online_status' => 1]);
                $result = Publication::myfilter(new Message(), $request->ids, [
                    [['online_status' => 1], 'ID为以下栏目还没上线'],
                ], '栏目下线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Message(), $ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '下线操作失败']);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('message.messages.publish_one_or_more')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Message(), $request->ids, [
                    [['online_status' => 0], 'ID为以下消息还未下线: '],
                    [['publish_down_status' => 0], 'ID为以下消息已经下线发布: '],
                ], '消息下线发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                /*
                 * 删除接口库中对应的数据
                 * 这里有两种可能的情况
                 * 1.资源还没有上线发布就被下线, 接口库没有还没有这个资源
                 * 2.资源已经上线发布过, 接口库中有这个资源
                 * 所以在删除接口库中的数据时, 需要先判断接口库中是否有对应数据, 有则返回删除操作的结果, 没有则直接返回true
                 */
                $messagesCount = DB::connection('interface')->table('messages')->whereIn('message_id', $ids)->count();
                if ($messagesCount) {
                    // 删除接口库中对应的数据
                    $result1 = Publication::deleteApi('messages', 'message_id', $ids);
                } else {
                    $result1 = true;
                }
                // 更新状态
                $result2 = Publication::updateMany(new Message(), $ids, [
                    'publish_down_status' => 1,
                    'publish_at'          => null,
                    'user_id'             => $user_id,
                ]);
                return response()->json(['status' => 'success', 'content' => $result1 && $result2 ? $content : '下线发布失败!']);
        }
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int)$request->input('taskid');
        return Publication::progress($taskid);
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Message::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '消息名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->datetimeRange('start_at', 'end_at', '有效期')->default(['start' => date('Y-m-d H:i:s', time()), 'end' => date('Y-m-d H:i:s', time())]);
            // $form->datetimeRange('startdate', 'enddate', '有效期')->default(['start' => date('Y-m-d H:i:s', time()), 'end' => date('Y-m-d H:i:s', time())]);
            $form->editor('long_desc', '消息内容')->help('必填');


            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Message::class, function (Grid $grid) {

            // 状态过滤
            // Publication::statusFilter($request->input('status'), $request->input('published'), $grid);

            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // //添加按钮
            // if (!\Gate::check('message.messages.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('message.messages.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('message.messages.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('message.messages.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('message.messages.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });
            // 表格中的按钮
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $id                  = $actions->getKey();
                // 上线按钮
                if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('message.messages.up')) {
                    $url      = route('message.messages.up');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'up',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                }
                // 下线按钮
                if ($online_status === 1 && Admin::user()->can('message.messages.down')) {
                    $url      = route('message.messages.down');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'down',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                }
                // 上线发布按钮
                if ($online_status === 1 && $publish_status === 0 && Admin::user()->can('message.messages.publish_one_or_more')) {
                    $url      = route('message.messages.publish_one_or_more');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publish',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                }
                // 下线发布按钮
                if ($publish_down_status === 0 && $online_status === 0 && Admin::user()->can('message.messages.publish_down_one_or_more')) {
                    $url      = route('message.messages.publish_down_one_or_more');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publishDown',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线发布"><i class="fa fa-cloud-download"></i></a>');
                }
                // 编辑按钮
                if (Admin::user()->cannot('message.messages.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('message.messages.destroy')) {
                    $actions->disableDelete();
                }
                // 只有状态下线的资源才可以编辑,删除
                if ($publish_down_status === 0) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                }
            });

            //添加按钮
            if (Admin::user()->cannot('message.messages.create')) {
                $grid->disableCreation();
            }


            //导出按钮
            if (Admin::user()->cannot('message.messages.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $url2 = route('message.messages.progress');
                // 下线发布功能
                if (Admin::user()->can('message.messages.publish_down')) {
                    $url      = route('message.messages.publish_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                }
                // 上线发布功能
                if (Admin::user()->can('message.messages.publish')) {
                    $url      = route('message.messages.publish');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                }
                // 全部下线功能
                if (Admin::user()->can('message.messages.all_down')) {
                    $url      = route('message.messages.all_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                }
                // 全部上线功能
                if (Admin::user()->can('message.messages.all_up')) {
                    $url      = route('message.messages.all_up');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                }
                // 过滤按钮
                // $tools->append(new \App\Admin\Extensions\Tools\Message\MessageStatus());
                // $tools->append(new \App\Admin\Extensions\Tools\Message\MessagePublished());
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('message.messages.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // 批量上线按钮
                    if (Admin::user()->can('message.messages.up')) {
                        $batch->add('上线', new \App\Admin\Extensions\Tools\Message\ReleaseMessage('up'));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('message.messages.down')) {
                        $batch->add('下线', new \App\Admin\Extensions\Tools\Message\ReleaseMessage('down'));
                    }
                    // 批量发布按钮
                    if (Admin::user()->can('message.messages.publish_one_or_more')) {
                        $batch->add('上线发布', new \App\Admin\Extensions\Tools\Message\ReleaseMessage('publish'));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('message.messages.publish_down_one')) {
                        $batch->add('下线发布', new \App\Admin\Extensions\Tools\Message\ReleaseMessage('publishDown'));
                    }
                });
            });

            $grid->column('name', '消息名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('long_desc', '消息内容')->display(function ($val) {
                return $val;
            });
            $grid->column('start_at', '开始时间')->sortable();
            $grid->column('end_at', '结束时间')->sortable();
            $grid->column('publish_at', '发布时间')->sortable();
            $grid->column('online_at', '上线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('offline_at', '下线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-red">下线</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">上线</span>';
                        break;
                    default:
                        return '未知';
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($this->online_status) {
                    case 0:
                        switch ($this->publish_down_status) {
                            case 0:
                                return '<span class="badge bg-red">下线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">下线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    case 1:
                        switch ($this->publish_status) {
                            case 0:
                                return '<span class="badge bg-red">上线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">上线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    default:
                        return '未知';
                }
            })->sortable();


            /**
             * 过滤处理
             */
            // $grid->filter(function ($filter) {
            // // 禁用id查询框
            // $filter->disableIdFilter();
            // // 名称
            // $filter->like('name', '内容模板类型名称');
            // // 模板别名
            // $filter->like('alias', '模板类型别名');
            // });
        });
    }
}
